<template>
  <div class="detail-container">
    <el-card>
      <!-- <div slot="header" class="table_header">
        <span>基础信息</span>
      </div> -->
      <div class="table_header">
        基础信息
      </div>
      <div>
        <el-row :gutter="20">
          <el-form ref="basicForm" :inline="false" label-position="right" :rules="rules" label-width="100px" :model="basicForm">
            <el-col :span="18">
              <el-form-item label="表单名称:" prop="formName">
                <el-input v-model.trim="basicForm.formName"  placeholder="请输入表单名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="活动类型:" prop="actTypeId">
                <searchSelect
                  placeholder="请搜索选择活动类型"
                  v-model="basicForm.actTypeId"
                  :loading="classifySelect.loading"
                  :options="classifySelect.options"
                  :filterable="true"
                  :total-pages="classifySelect.total"
                  :current.sync="classifySelect.current"
                  :size.sync="classifySelect.size"
                  @getOption="getClassifyOptions"
                  @change="classifyChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button size="small" @click="handleInsertNewClassify">新建分类</el-button>
            </el-col>
            <el-col :span="18">
              <el-form-item label="流程:" prop="flowId">
                <searchSelect
                 placeholder="请搜索选择流程"
                  v-model="basicForm.flowId"
                  :loading="templateSelect.loading"
                  :options="templateSelect.options"
                  :filterable="true"
                  :total-pages="templateSelect.total"
                  :current.sync="templateSelect.current"
                  :size.sync="templateSelect.size"
                  @getOption="getprocessOptions"
                  @change="templateChange"
                />

              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <!-- <div slot="header" class="table_header">
        <span>考核类型</span>
        <div>
          <el-button size="small" type="primary">排序</el-button>
        </div>
      </div> -->
      <div class="table_header">
        <span>考核类型</span>
        <div>
          <el-button size="small" type="primary" @click="handleStartSort">排序</el-button>
        </div>
      </div>
      <classify-dom v-if="!hasClassify" :list="classifyList" @choose="handleClassifyChoose" />
      <div v-else class="classify-box">
        <div v-for="(item,index) in (classifyList.filter(i=>i.show))" :key="index" class="classify-item">
          <div class="title" @click.stop="handleTitleClick(item)">
            <div><i :class="item.showList ? 'el-icon-caret-top' : 'el-icon-caret-bottom'" />{{ item.name }}</div>
            <div><el-button type="text" size="small" @click="handleDeleteClassify(item.key)">删除</el-button></div>
          </div>
          <div v-if="item.list.length > 0" :class="{'list':true,'hide-list':!item.showList}">
            <classify-item v-show="item.showList" :list="item.list" :classify-key="item.key" @deleteitem="handleDeleteClassifyItemList" />
          </div>
          <div class="button">
            <el-button @click.stop="handleAddPoint(item)">指标库导入</el-button>
          </div>
        </div>
        <div v-show="hasAllClassify()" class="classify-item classify-add" @click.stop="handleShowClassifyDialog">
          <i class="el-icon-plus" /> 添加考核类型
        </div>
      </div>
      <div class="btn-save">
        <el-button size="small" type="primary" @click="submitForm('basicForm')">保存</el-button>
      </div>
    </el-card>
    <el-dialog
      title="考核类型"
      :visible.sync="classifyDialogVisible"
      width="60%"
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="handleClassifyDialogClose"
    >
      <classify-dom :list="classifyList" @choose="handleClassifyChoose" />
    </el-dialog>
    <el-dialog
      title="指标库导入"
      :visible.sync="pointDialogVisible"
      width="60%"
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="handlePointDialogClose"
    >
      <point-dom :visible="pointDialogVisible" :index-type="indexType" :list="chooseClassifyList" @close="pointDialogVisible=false" @save="handlePointSave" />
    </el-dialog>
    <el-dialog
      title="考核排序"
      :visible.sync="sortDialogVisible"
      width="60%"
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="handleSortDialogClose"
    >
      <sort-dom :visible="sortDialogVisible" :list="sortList" @close="sortDialogVisible=false" @save="handleSortSave" />
    </el-dialog>
    <el-dialog
      title="新建分类"
      :visible.sync="newClassifyDialogVisible"
      width="30%"
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="newClassifyForm"
        :inline="true"
        :model="newClassifyForm"
        label-width="120px"
        :rules="{name:[{ required: true, message: '请输入分类名称', trigger: 'blur' },]}"
      >
        <el-form-item label="分类名称:" prop="name">
          <el-input v-model.trim="newClassifyForm.name"   placeholder="请输入分类名称" style="width: 100%" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align:right;">
        <el-button @click="newClassifyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveNewClassify('newClassifyForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ClassifyDom from './classify'
import ClassifyItem from './classifyItem'
import PointDom from './pointList'
import SortDom from './sortList'
import searchSelect from '@/components/SearchSelect'
export default {
  name: 'FormManagerDetail',
  components: { ClassifyDom, ClassifyItem, PointDom, SortDom, searchSelect },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      indexType: -1,
      classifyDialogVisible: false,
      pointDialogVisible: false,
      sortDialogVisible: false,
      newClassifyDialogVisible: false, // 新建分类
      formId: '',
      basicForm: {
        formName: '', // 表单名称
        actTypeId: '', // 活动类型id
        actTypeName: '', // 活东名称
        flowId: '', // 流程id
        flowName: '', // 流程名称
        id: ''

      },
      rules: {
        formName: [
          { required: true, message: '请输入表单名称', trigger: ['change', 'blur'] }

        ],
        actTypeId: [
          { required: true, message: '请选择活动类型', trigger: ['change', 'blur'] }
        ],
        flowId: [
          { required: true, message: '请选择流程', trigger: ['change', 'blur'] }
        ]

      },
      processOptions: [],
      classifyOptions: [],
      hasClassify: false,
      classifySelect: {
        options: [],
        loading: false,
        total: 0,
        current: 1,
        size: 20
      },
      templateSelect: {
        options: [],
        loading: false,
        total: 0,
        current: 1,
        size: 20
      },
      classifyList: [
        {
          name: '加分项',
          icon: require('@/assets/formManager/icon2.png'),
          icon1: require('@/assets/formManager/icon2_1.png'),
          show: false,
          key: 'add',
          showList: false,
          indexType: 0,
          totalPages: 0,
          list: []

        },
        {
          name: '减分项',
          icon: require('@/assets/formManager/icon1.png'),
          icon1: require('@/assets/formManager/icon1_1.png'),
          show: false,
          key: 'delete',
          showList: false,
          indexType: 1,
          totalPages: 0,
          list: []

        },
        {
          name: '加减分项',
          icon: require('@/assets/formManager/icon5.png'),
          icon1: require('@/assets/formManager/icon5_1.png'),
          show: false,
          key: 'adddelete',
          showList: false,
          indexType: 2,
          list: []
        },
        {
          name: '自定义加分项',
          icon: require('@/assets/formManager/icon3.png'),
          icon1: require('@/assets/formManager/icon3_1.png'),
          show: false,
          key: 'addcustom',
          showList: false,
          indexType: 3,
          totalPages: 0,
          list: []
        },
        {
          name: '自定义减分项',
          icon: require('@/assets/formManager/icon4.png'),
          icon1: require('@/assets/formManager/icon4_1.png'),
          show: false,
          key: 'deletecustom',
          showList: false,
          indexType: 4,
          totalPages: 0,
          list: []
        }
      ],
      chooseClassifyKey: -1,
      chooseClassifyList: [],
      isRule: false,
      sortList: [],
      newClassifyForm: {
        name: ''
      }
    }
  },
  computed: {

  },
  watch: {

  },

  created() {
    if (this.isEdit) {
      this.formId = this.$route.query && this.$route.query.id
      this.$nextTick(() => {
        this.fetchData(this.formId)
      })
    }
    this.initSelectOption()
  },
  methods: {
    // 表单保存
    submitForm(formName) {
      var that = this
      const flag = that.classifyList.findIndex((item) => item.show === true) === -1
      if (flag) {
        that.$message({
          message: '至少选择一个考核类型',
          type: 'error'
        })
        return
      } else {
        that.classifyList.map((item, index) => {
          if (item.show === true) {
            if (item.list.length === 0) {
              that.$message({
                message: '已选择考核类型至少选择一个考核项',
                type: 'error'
              })
              return
            } else {
              this.isRule = true
            }
          }
        })
        if (this.isRule) {

          that.$refs[formName].validate((valid) => {
            if (valid) {
              const setarr = []
              if (that.sortList.length > 0) {
                that.sortList.map((item, index) => {
                  setarr.push({ modelName: item.modelName, itemId: item.id })
                })
              } else if (that.sortList.length === 0) {
                that.classifyList.map((item, index) => {
                  item.list.map((it) => {
                    setarr.push({ modelName: '', itemId: it.id })
                  })
                })
              }

              let params = this.basicForm
              if (params.id === '') {
                params.formRelationShips = setarr
                params = JSON.stringify(params)
                that.$Http.formNewSubmission(params).then(res => {
                  if (res.code === 200) {
                    this.$message({
                      message: res.message,
                      type: 'success'
                    })
                    this.$router.go(-1)
                  } else {
                    this.$message({
                      message: res.message,
                      type: 'error'
                    })
                  }
                }).catch(err => {
                  this.$message({
                    message: err,
                    type: 'error'
                  })
                })
              } else {
                params.formRelationShips = setarr
                params = JSON.stringify(params)
                that.$Http.setfetchData(params).then(res => {
                  if (res.code === 200) {
                    this.$message({
                      message: res.message,
                      type: 'success'
                    })
                    this.$router.go(-1)
                  } else {
                    this.$message({
                      message: res.message,
                      type: 'error'
                    })
                  }
                }).catch(err => {
                  this.$message({
                    message: err,
                    type: 'error'
                  })
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }
      }
    },
    classifyChange(el) {
      this.classifySelect.options.map((item, index) => {
        if (el === item.id) {
          this.basicForm.actTypeName = item.label
        }
      })
    },
    templateChange(el) {
      this.templateSelect.options.map((item, index) => {
        if (el === item.id) {
          this.basicForm.flowName = item.label
        }
      })
    },
    initSelectOption() {
      this.classifySelect.current = 1
      this.templateSelect.current = 1

      this.getClassifyOptions({
        current: this.classifySelect.current,
        size: this.classifySelect.size
      })
      this.getprocessOptions({
        current: this.templateSelect.current,
        size: this.templateSelect.size
      })
    },
    // 获取活动类型分类
    getClassifyOptions(data) {
      const {
        pageInfo,
        searchValue
      } = data
      const params = Object.assign({}, pageInfo)
      if (searchValue) params.actTypeName = searchValue
      this.classifySelect.loading = true
      this.$Http.getActivityType(params).then((response) => {
        this.classifySelect.loading = false
        const {
          result
        } = response
        this.classifySelect.total = result.totalRows
        if (Array.isArray(result.resultData)) {
          this.classifySelect.options = result.resultData.map((info) => {
            return {
              value: info.id,
              label: info.actTypeName,
              id: info.id
            }
          })
        }
      })
        .catch((error) => {
          this.classifySelect.loading = false
          console.log(error)
        })
    },
    // 获取流程列表
    getprocessOptions(data) {
      const {
        pageInfo,
        searchValue
      } = data
      const params = Object.assign({}, pageInfo)
      if (searchValue) params.templateName = searchValue
      this.templateSelect.loading = true
      this.$Http.getFlowTemplateinfoPageList(params).then((response) => {
        this.templateSelect.loading = false
        const {
          result
        } = response
        this.templateSelect.total = result.totalRows
        if (Array.isArray(result.resultData)) {
          this.templateSelect.options = result.resultData.map((info) => {
            return {
              value: info.id,
              label: info.templateName,
              id: info.id
            }
          })
        }
      })
        .catch((error) => {
          this.templateSelect.loading = false
          console.log(error)
        })
    },
    hasAllClassify() {
      const index = this.classifyList.findIndex(i => i.show === false)
      return !!(index > -1)
    },
    judgeHasClassify() {
      const index = this.classifyList.findIndex(i => i.show === true)
      return !!(index > -1)
    },
    async fetchData(id) {
      try {
        const res = await this.$Http.getfetchData({ id: id })
        if (res.code === 200) {
          for (const i in this.basicForm) {
            this.basicForm[i] = res.result[i]
          }
          if (res.result.hkFormResultVos.length > 0) {
            res.result.hkFormResultVos.map((item, index) => {
              this.classifyList.map((it, i) => {
                if (item.indexTypeName === it.indexType) {
                  this.$nextTick(() => {
                    it.list = item.hkAssessmentIndices
                    this.handleClassifyChoose(it.key)
                    this.classifyList[i].showList = true

                    this.$forceUpdate()
                  })

                  item.hkAssessmentIndices.map((i) => {
                    this.chooseClassifyList.push(i)
                  })
                }
              })
            })
          }
        }
      } catch (err) {
        console.log('err', err)
      }
    },
    handleClassifyDialogClose(done) {
      done()
    },
    handleShowClassifyDialog() {
      this.classifyDialogVisible = true
    },
    handleClassifyChoose(key) {
      const index = this.classifyList.findIndex(i => i.key === key)
      if (index > -1) {
        const data = this.classifyList[index]
        data.show = true
        this.classifyList.splice(index, 1, data)
        this.hasClassify = true
      }
      this.classifyDialogVisible = false
    },
    handleDeleteClassify(key) {
      const index = this.classifyList.findIndex(i => i.key === key)
      if (index > -1) {
        const data = this.classifyList[index]
        data.show = false
        data.list = []
        this.classifyList.splice(index, 1, data)
      }
      this.hasClassify = this.judgeHasClassify()
    },
    async handleAddPoint(item) {
      this.chooseClassifyKey = item.key
      this.chooseClassifyList = item.list
      this.indexType = item.indexType
      this.pointDialogVisible = true
    },
    handlePointDialogClose(done) {
      done()
    },
    // 去重
    duplicateRemoval(arr) {
          const res = new Map();
          return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, arr.id));
        },

    //
    handlePointSave(list) {

      if (this.chooseClassifyKey) {

        const index = this.classifyList.findIndex(i => i.key === this.chooseClassifyKey)
        const data = this.classifyList[index]
        data.list = data.list.concat(list)
        data.list= this.duplicateRemoval(data.list)

        data.showList = true
        this.classifyList.splice(index, 1, data)
        this.$nextTick(() => {
          this.chooseClassifyKey = ''
        })
      }
    },
    handleDeleteClassifyItemList(info) {
      const { index, key } = info
      if (key && index > -1) {
        const index1 = this.classifyList.findIndex(i => i.key === key)
        const data = this.classifyList[index1]
        data.list.splice(index, 1)
        this.classifyList.splice(index1, 1, data)
      }
    },
    handleSortDialogClose(done) {
      done()
    },
    // 点击排序
    handleStartSort() {


      // 先获取到之前排序的顺序，先按照之前排序的顺序排，新增的放到后面，用不同颜色标记
      const list = this.classifyList.reduce((pre, next) => {
        return pre.concat(next.list)
      }, [])
      console.log('list啊啊啊啊',list)
      list.sort((p1,p2)=>{
      return p1.sortNumber-p2.sortNumber

      })
      if (list.length > 0) {
        const listIds = list.reduce((pre, next) => {
          return pre + ',' + next.id
        }, '')
        const newSortList = []
        if (this.sortList.length > 0) {
          // 按照之前的排序
          // 先看看之前的数据是不是还在sortList里
          this.sortList.forEach(i => {
            if (listIds.includes(i.id)) {
              // 把这条记录从list剔除
              const index = list.findIndex(l => l.id === i.id)
              list.splice(index, 1)
              i.isOld = true
              newSortList.push(i)
            }
          })
        }
        this.sortList = [].concat(newSortList).concat(list)
        this.$nextTick(() => {
          this.sortDialogVisible = true
        })
      } else {
        this.$message.error('请先选择考核类型并导入指标库')
      }
    },
    // 排序保存
    handleSortSave(list) {
      this.sortList = [].concat(list)
    },
    // 新建分类
    handleInsertNewClassify() {
      this.newClassifyDialogVisible = true
    },
    handleSaveNewClassify(formName) {
      const dom = this.$refs[formName]
      if (dom) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.confirmSaveNewClassify(formName)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    async confirmSaveNewClassify(formName) {
      try {
        const { newClassifyForm } = this
        const res = await this.$Http.newActivityType({ actTypeName: newClassifyForm.name })
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: res.message
          })
          this.newClassifyDialogVisible = false
          this.$refs[formName].resetFields()
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      } catch (err) {
        console.error(err)
        this.$message({
          type: 'error',
          message: err
        })
      }
    },
    handleTitleClick(item) {
      item.showList = !item.showList
    }
  }
}
</script>
<style></style>
<style lang='scss' scope>
.detail-container{
  padding:10px 10px 0 10px;
  width: 100%;
  // transform: translateZ(0);
  .header{
    text-align: right;
    margin-bottom: 10px;
    position: fixed;
    width: 100%;
    height: 50px;
    z-index: 9;
    background: #FFF;
    margin-top: -10px;
    line-height: 50px;
    padding: 0 20px;
  }
  .table_header{
      font-weight: bold;
      color:#000;
      height:50px;
      display:flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
  }
  .classify-box{
    max-height: 500px;
    overflow-y: scroll;
    padding: 10px 0;
    .classify-add{
      // line-height: 30px;
      &:hover{
        cursor: pointer;
      }
    }
    .classify-item{
      margin-top:10px;
      padding:20px 10px;
      border: 1px solid #ddd;
      border-radius: 10px;
      box-sizing:border-box;
      .title{
        height:30px;
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
        :hover{
          cursor: pointer;
        }
      }
      .list{
        transition: all 0.5s;
      }
      .hide-list{
        height:0
      }
      .button{
        margin-top:10px;
      }
      &:first-child{
        margin-top:0;
      }
    }
  }
  .btn-save{
      text-align: right;
      margin-top: 20px;
      border-top: 1px solid #eee;
      padding-top: 10px;
    }
}
</style>
